package com.mxpio.erp.technology.service.impl;

import com.alibaba.excel.EasyExcel;
import com.mxpio.erp.common.EasyexcelCommonListener;
import com.mxpio.erp.common.technology.entity.BomInfo;
import com.mxpio.erp.common.technology.entity.BomInfoLine;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.entity.ItemMaterialProp;
import com.mxpio.erp.common.technology.service.EasyexcelUploadForTechService;
import com.mxpio.erp.common.technology.vo.BomInfoImportModel;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.jpa.JpaUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author : wpp
 * @Datetime : 2023/3/21 9:51
 * @Desc :
 * @Modor :  Modifytime:
 * @modDesc :
 */
@Service
public class EasyexcelUploadForTechServiceImpl implements EasyexcelUploadForTechService {
    @Override
    @Transactional
    public List<BomInfoImportModel> uploadBom(InputStream inputStream) throws ParseException {
        EasyexcelCommonListener<BomInfoImportModel> excelListener = new EasyexcelCommonListener<>();
        EasyExcel.read(inputStream,BomInfoImportModel.class,excelListener).sheet().doRead();
        List<BomInfoImportModel> modelList = excelListener.getList();

        int size = modelList == null ? 0 : modelList.size();
        if (size==0){
            throw new MBootException("上传文件的不能为空或Excle数据都不正确");
        }
        if (size > 10000) {
            throw new MBootException("上传的文件不能超过1万条数据");
        }

        Set<String> parentCodeSet = new HashSet<>();
        Set<String> itemCodeSet = new HashSet<>();
        modelList.forEach(m -> {
            parentCodeSet.add(m.getParentCode());
            itemCodeSet.add(m.getItemCode());
        });
        List<Item> parentItemList = JpaUtil.linq(Item.class).in("itemCode", parentCodeSet).list();
        Map<String, Item> parentItemMap = null;
        if (parentItemList.size()>0){
            parentItemMap = JpaUtil.index(parentItemList,"itemCode");//查询物料
        }else{
            throw new MBootException("上传文件中的父物料编码均不存在");
        }
        List<Item> subItemList = JpaUtil.linq(Item.class).in("itemCode", itemCodeSet).list();
        //List<ItemMaterialProp> materialProps =  JpaUtil.linq(ItemMaterialProp.class).equal("propType", "item").in("code", itemCodeSet).list();
        //Map<String, ItemMaterialProp> materialPropMap = JpaUtil.index(materialProps,"code");
        Map<String, Item> subItemMap = null;
        if (subItemList.size()>0){
            subItemMap = JpaUtil.index(subItemList,"itemCode");//查询物料
        }else{
            throw new MBootException("上传文件中的子物料编码均不存在");
        }
        List<BomInfo> bomInfoList = JpaUtil.linq(BomInfo.class).in("parentCode", parentCodeSet).list();
        Map<String, BomInfo> bomInfoMap = null;
        if (bomInfoList.size()>0){
            bomInfoMap = JpaUtil.index(bomInfoList,"parentCode");//查询套机;
        }

        Set<String> rowIdSet = new HashSet<>();
        List<BomInfoImportModel> succImportModelList = new ArrayList<>();
        for (BomInfoImportModel model : modelList) {
            if (StringUtils.isBlank(model.getParentCode())) {
                model.fail("父级物料编码为空");
                continue;
            }
            if (StringUtils.isBlank(model.getItemCode())) {
                model.fail("子级物料编码为空");
                continue;
            }

            boolean flag = true;
            StringBuffer sb = new StringBuffer();
            String parentCode = model.getParentCode();
            String itemCode = model.getItemCode();
            BigDecimal itemConsumption = model.getItemConsumption();//单台数量
            BigDecimal makeLength = model.getMakeLength();//下料长度
            BigDecimal makeArea = model.getMakeArea();//宽度
            BigDecimal makeNum = model.getMakeNum();//数量 可制数量
            String rowIdStr = parentCode + "_" + itemCode ;
            boolean itemSetFlag = false;
            if (!parentItemMap.containsKey(parentCode)) {
                flag = false;
                sb.append("父级物料编码不存在;");
            }
            if (bomInfoMap!=null&&bomInfoMap.containsKey(parentCode)){
                flag = false;
                sb.append("系统中已存在生效的bom信息;");
            }
            if (!subItemMap.containsKey(itemCode)) {
                flag = false;
                sb.append("子级物料编码不存在;");
            }
            if (rowIdSet.contains(rowIdStr)) {
                flag = false;
                sb.append("存在“父级物料编码+子级物料编码”相同的其他行数据;");
            } else {
                rowIdSet.add(rowIdStr);
            }
            if (flag) {
                model.setImportSuccess("成功");
                model.setImportMsg("导入成功");
            } else {
                model.setImportSuccess("失败");
                model.setImportMsg(sb.toString());
                continue;
            }
            succImportModelList.add(model);
        }
        //处理验证通过数据
        if (succImportModelList.size()>0){
            Map<String, List<BomInfoImportModel>> map = succImportModelList.stream().collect(Collectors.groupingBy(BomInfoImportModel::getParentCode));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (String key: map.keySet()){
                BomInfo bomInfo = new BomInfo();
                bomInfo.setBeginTime(sdf.parse("2022-12-31"));
                bomInfo.setEndTime(sdf.parse("2099-12-31"));
                bomInfo.setPrimaryBom("1");
                bomInfo.setVersion("V1.0");
                bomInfo.setUseType("03");//生效中
                bomInfo.setParentCode(key);
                Item parentItem = parentItemMap.get(key);
                bomInfo.setParentName(parentItem.getItemName());
                bomInfo.setParentSpec(parentItem.getItemSpec());
                bomInfo.setParentDrawingNo(parentItem.getDrawingNo());
                bomInfo.setParentUnit(parentItem.getUnitCode());
                bomInfo.setParentGroup(parentItem.getItemGroupCode());
                JpaUtil.save(bomInfo);

                //处理明细
                List<BomInfoImportModel> submodelList = map.get(key);
                List<BomInfoLine> lineList = new ArrayList<>();
                int lineNo = 0;
                for (BomInfoImportModel per:submodelList){
                    lineNo++;
                    BomInfoLine line = new BomInfoLine();
                    line.setBomId(bomInfo.getParentCode());//取parentcode而非bominfo.id
                    line.setLineNo(lineNo+"");
                    line.setBeginTime(sdf.parse("2022-12-31"));
                    line.setEndTime(sdf.parse("2099-12-31"));
                    Item subItem = subItemMap.get(per.getItemCode());
                    line.setItemCode(subItem.getItemCode());
                    line.setItemName(subItem.getItemName());
                    line.setItemProp(subItem.getItemGroupCode());
                    line.setItemSpec(subItem.getItemSpec());
                    line.setDrawingNo(subItem.getDrawingNo());
                    line.setMaterial(subItem.getMaterial());
                    line.setMaterialBrand(subItem.getMaterialBrand());//材料牌号
                    /*ItemMaterialProp itemMaterialProp = materialPropMap.get(per.getItemCode());
                    if (itemMaterialProp!=null){
                        line.setMaterialBrand(itemMaterialProp.getMaterialBrand());//材料牌号
                    }*/

                    if (per.getItemConsumption()!=null){
                        line.setItemConsumption(per.getItemConsumption());
                    }else{//零件
                        line.setMakeLength(per.getMakeLength());
                        line.setMakeArea(per.getMakeArea());
                        line.setMakeNum(per.getMakeNum());
                        line.setItemConsumption(new BigDecimal("1000"));
                    }
                    lineList.add(line);
                }
                if (lineList.size()>0){
                    JpaUtil.save(lineList);
                }
            }
        }
        return modelList;
    }
}
